using Azure;
using JTZY.Admin.WebApi.Filters;
using JTZY.Model.Product;
using JTZY.Model.Product.Dto;
using JTZY.Model.Stock;
using JTZY.Model.Stock.Dto;
using JTZY.Service.Business;
using JTZY.Service.Business.IBusinessService;
using JTZY.Service.Goods.IGoodsService;
using JTZY.Service.Order;
using JTZY.Service.Product.IProductService;
using JTZY.Service.Stock.IStockService;
using Microsoft.AspNetCore.Mvc;

//创建时间：2024-12-30
namespace JTZY.Admin.WebApi.Controllers.Stock
{
    /// <summary>
    /// 调仓单
    /// </summary>
    [Verify]
    [Route("stock/Transferorder")]
    public class TransferorderController : BaseController
    {
        /// <summary>
        /// 调仓单接口
        /// </summary>
        private readonly ITransferorderService _TransferorderService;
        private readonly ICorecmsuserstockService _usService;
        private readonly ICorecmsuserService _corecmsuserService;
        private readonly IProdinfoService _ProdinfoService;

        public TransferorderController(ITransferorderService TransferorderService, IProdinfoService ProdinfoService,ICorecmsuserService corecmsuserService
            , ICorecmsuserstockService usService)
        {
            _TransferorderService = TransferorderService;
            _usService = usService;
            _corecmsuserService = corecmsuserService;
            _ProdinfoService = ProdinfoService;

        }

        /// <summary>
        /// 查询调仓单列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("list")]
        [ActionPermissionFilter(Permission = "transferorder:list")]
        public IActionResult QueryTransferorder([FromQuery] TransferorderQueryDto parm)
        {
            parm.UserId = HttpContext.GetUId();
            var response = _TransferorderService.GetList(parm);
            return SUCCESS(response);
        }


        /// <summary>
        /// 查询调仓单详情
        /// </summary>
        /// <param name="OrderId"></param>
        /// <returns></returns>
        [HttpGet("{OrderId}")]
        [ActionPermissionFilter(Permission = "transferorder:query")]
        public IActionResult GetTransferorder(string OrderId)
        {
            var response = _TransferorderService.GetInfo(OrderId);
            
            var info = response.Adapt<TransferorderDto>();
            return SUCCESS(info);
        }

        /// <summary>
        /// 添加调仓单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionPermissionFilter(Permission = "transferorder:add")]
        [Log(Title = "调仓单", BusinessType = BusinessType.INSERT)]
        public IActionResult AddTransferorder([FromBody] TransferorderDto parm)
        {
            var userId = HttpContext.GetUId();

            parm.UserId = userId;

            var modal = parm.Adapt<Transferorder>().ToCreate(HttpContext);

            parm.CreateTime = DateTime.Now;
            if (modal.Type == "1")//调回本仓
            {
                modal.NewUserld = userId;
            }

            modal.OldUserId = userId;

            var result = _TransferorderService.AddTransferorder(modal);
            if (result.status) 
            {
                return SUCCESS(result.data);
            }
            //return SUCCESS(response);
            return ToResponse(ResultCode.FAIL, result.msg);
        }

        /// <summary>
        /// 更新调仓单
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        [ActionPermissionFilter(Permission = "transferorder:edit")]
        [Log(Title = "调仓单", BusinessType = BusinessType.UPDATE)]
        public IActionResult UpdateTransferorder([FromBody] TransferorderDto parm)
        {
            var modal = parm.Adapt<Transferorder>().ToUpdate(HttpContext);
            var response = _TransferorderService.UpdateTransferorder(modal);

            return ToResponse(response);
        }

        /// <summary>
        /// 查询货物表详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost("getprodinfobycode")]
        [ActionPermissionFilter(Permission = "prodinfo:query")]
        public IActionResult GetProdinfoByCode([FromBody] ProdQueryDto param)
        {
            var no = "";
            var f = "";
            if (string.IsNullOrEmpty(param.snCode))
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "未检测到物码");

            }
            if (param.snCode.Contains("http"))
            {
                var Querys = UrlStringHelper.GetQueryDictionary(param.snCode);
                if (Querys.Keys.Contains("no"))
                    no = Querys["no"];
                if (Querys.Keys.Contains("n"))
                    no = Querys["n"];
                if (Querys.Keys.Contains("f"))
                    f = Querys["f"];
                if (string.IsNullOrEmpty(f))
                {
                    f = "n";
                }
                if (f.ToLower() != "w" && (param.type == "1" || param.type == "0" || param.type == "3"))
                {
                    return ToResponse(ResultCode.CUSTOM_ERROR, "商品打包请扫盒子码");
                }
            }
            else
            {
                no = param.snCode;
            }
            var userId = HttpContext.GetUId();
            Prodinfo response = null;
            if (string.IsNullOrEmpty(f))
            {
                response = _ProdinfoService.GetProdinfoByCode(no, "w");
                if (response == null)
                    response = _ProdinfoService.GetProdinfoByCode(no, "n");
            }
            else
            {
                response = _ProdinfoService.GetProdinfoByCode(no, f);
            }
            if (param.type == "1" || param.type == "0")
            {


                if (response == null)
                {
                    return ToResponse(ResultCode.CUSTOM_ERROR, "此商品未入库");
                }

                if (response != null && response.UserId.HasValue && response.UserId.Value > 0 && response.UserId != userId)
                {
                    return ToResponse(ResultCode.CUSTOM_ERROR, "此商品不属于您");
                }

                //if (response.UserCusId.HasValue&& response.UserCusId>0 && param.type == "1")
                //{
                //    return ToResponse(ResultCode.CUSTOM_ERROR, "小仓商品，请调回本仓再操作");
                //}

                if (response.Status == 2)
                {
                    return ToResponse(ResultCode.CUSTOM_ERROR, "此商品已出库");
                }

                if (response.Status == 0)
                {
                    return ToResponse(ResultCode.CUSTOM_ERROR, "此商品未入库");
                }

                if (response.IsReturn == 1)
                {
                    return ToResponse(ResultCode.CUSTOM_ERROR, "此商品已退库");
                }

            }

            //if (param.type == "0" || param.type == "2")
            //{
            //    if (response.Status == 1)
            //    {
            //        return ToResponse(ResultCode.CUSTOM_ERROR, "此商品已入库，请勿重复");
            //    }
            //}

            if (!response.UserCusId.HasValue || response.UserCusId==0)
            {
                if (param.type == "1")
                {
                    return ToResponse(ResultCode.CUSTOM_ERROR, "非小仓商品，无需调回本仓");
                }
            }

            var info = response.Adapt<ProdinfoDto>();
            var prod = _usService.Queryable().Where(us => us.UserId == userId && us.ProductId == response.ProductId).First();
            decimal price = response.CostPrice ?? 0;
            if (response.UserCusId > 0 || param.UserId.HasValue)
            {
                var user = _corecmsuserService.GetById(response.UserCusId > 0 ? response.UserCusId : param.UserId);
                if (user != null)
                {
                    switch (user.Level)
                    {
                        case "0":
                            price = prod.Vip0;
                            break;
                        case "1":
                            price = prod.Vip1;
                            break;
                        case "2":
                            price = prod.Vip2;
                            break;
                        case "3":
                            price = prod.Vip3;
                            break;
                        case "4":
                            price = prod.Vip4;
                            break;
                    }
                }
            }
            if (prod != null)
            {
                info.SkuImage = prod.SkuImage;
                info.SkuName = prod.SkuName;
                info.BarCode = prod.BarCode;
                info.Sn = prod.Sn;
                info.Price = price;
            }
            return SUCCESS(info);
        }

        /// <summary>
        /// 删除调仓单
        /// </summary>
        /// <returns></returns>
        [HttpPost("delete/{ids}")]
        [ActionPermissionFilter(Permission = "transferorder:delete")]
        [Log(Title = "调仓单", BusinessType = BusinessType.DELETE)]
        public IActionResult DeleteTransferorder([FromRoute]string ids)
        {
            var idArr = Tools.SplitAndConvert<string>(ids);

            return ToResponse(_TransferorderService.Delete(idArr));
        }
        /// <summary>
        /// 添加调仓单
        /// </summary>
        /// <returns></returns>
        [HttpPost("ItemsPacking")]
        [ActionPermissionFilter(Permission = "transferorder:ItemsPacking")]
        [Log(Title = "调仓单", BusinessType = BusinessType.UPDATE)]
        public IActionResult ItemsPacking([FromBody] TransferorderDto parm)
        {
            var userId = HttpContext.GetUId();

            parm.UserId = userId;
            var modal = parm.Adapt<Transferorder>().ToCreate(HttpContext);
            parm.UpdateTime= DateTime.Now;
            var result = _TransferorderService.ItemsPacking(modal);
            if (result.status)
            {
                return SUCCESS("");
            }
            //return SUCCESS(response);
            return ToResponse(ResultCode.FAIL, result.msg);
        }

        [HttpGet("cancel/{OrderId}")]
        [ActionPermissionFilter(Permission = "transferorder:cancelorder")]
        public IActionResult CancelOrder(string OrderId)
        {
            var result = _TransferorderService.CancelOrder(OrderId);

            if (result.status)
            {
                return SUCCESS("");
            }
            return ToResponse(ResultCode.FAIL, result.msg);
        }
    }
}